import { Address } from '@/types/address';
import { User, UserLoginParams } from '@/types/user';

import request from '../utils/request';
import { RequestConfig } from '../utils/request/type';
import Storage from '../utils/storage';
import { API_MAP } from './apiMap';

export class commonApi {
  static getSmsCode({ phone }: { phone: string }): Promise<any> {
    return request.get(API_MAP.SMS_CODE, { phone }).then((res: any) => {
      if (res.code === 200) {
        return res?.result;
      }
      throw new Error(res.message);
    });
  }

  static login({ encrypt }: UserLoginParams, config?: RequestConfig): Promise<User> {
    return request.post(API_MAP.LOGIN, { encrypt }, { ...config }).then((res: any) => {
      Storage.login.set(res?.result);
      return res?.result;
    });
  }
  /**
   * Retrieves the Weixin configuration.
   *
   * @return {Promise<any>} A Promise that resolves to the Weixin configuration.
   */
  static getWeixinConfig(): Promise<any> {
    return request
      .get(API_MAP.GET_WEIXIN_CONFIG, {
        url: window.location.href
      })
      .then((res: any) => res?.result);
  }

  static addressList(): Promise<any> {
    return request.get(API_MAP.ADDRESS_LIST).then((res: any) => res.result?.records);
  }
  static addUserAddress(params: Partial<Omit<Address, 'id'>>): Promise<any> {
    return request.post(API_MAP.ADD_ADDRESS, params).then((res: any) => res.result);
  }
  static updateUserAddress(params: Address): Promise<any> {
    return request.post(API_MAP.EDIT_ADDRESS, params).then((res: any) => res.result);
  }
}
